package com.scs.application.modules.msg.sender;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.EmailTemplate;
import com.scs.application.modules.msg.model.EmailMessage;
import com.scs.application.modules.msg.service.EmailTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 */
@Slf4j
@Component
public class EmailMessageSender extends MessageSender<EmailMessage> {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired(required = false)
    private EmailTemplateService emailTemplateService;

    @Override
    protected void beforeSend(EmailMessage msg) {
        super.beforeSend(msg);
        if (StringUtils.isBlank(msg.getTo())) {
            throw new BusinessException("邮件发送失败：接收邮箱不能为空");
        }

        if (StringUtils.isNoneBlank(msg.getTplKey()) && emailTemplateService == null) {
            throw new BusinessException("邮件发送失败：邮件模板服务实例不能为空");
        }
    }

    @Override
    protected void doSend(EmailMessage msg) {

        if (StringUtils.isNotBlank(msg.getTplKey())) {
            EmailTemplate emailTemplate = emailTemplateService.getOne(
                    Wrappers.<EmailTemplate>query()
                            .eq("tpl_key", msg.getTplKey())
                            .last("limit 1")
            );

            if (emailTemplate == null) {
                throw new BusinessException(String.format("邮件发送失败：邮件模板[%s]不存在", msg.getTplKey()));
            }
            msg.setTitle(emailTemplate.getTitle());
            msg.setContent(emailTemplate.getContent());
        }
        String title = msg.getTitle();
        String content = msg.getContent();

        // todo 标题、内容 模板引擎渲染
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper message = null;
        try {
            message = new MimeMessageHelper(mimeMessage, true);
            InternetAddress from = new InternetAddress(mailSender.getUsername(), "邮件测试服务", "UTF-8");
            message.setFrom(from);
            message.setTo(msg.getTo());
            message.setSubject(title);
            message.setText(content, true);

            if (StringUtils.isNotBlank(msg.getCc())) {
                message.setCc(msg.getCc());
            }
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BusinessException("邮件发送失败", e);
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("邮件发送失败", e);
        }
        log.debug("邮件发送成功，接收邮箱：{}", msg.getTo());
    }
}
